import fs from 'node:fs/promises';
import path from 'node:path';
import { color } from '../../core/color.js';
import { loadConfig } from '../../core/config.js';
import { Indent, Highlight, HighlightGreen } from '../../core/constants.js';
import { logger } from '../../core/logger.js';
import { Command } from '../utils/cli-handler.js';
import { createRequire } from 'node:module';
import { exec } from '../utils/utils.js';
import { getPackageManager } from '../utils/runtime-utils.js';
import { Spinner } from '../utils/spinner.js';
import { existsSync } from 'node:fs';

const require2 = createRequire(import.meta.url);
const command = new Command("remove").description("Removes a plugin from your Robo").option("-f", "--force", "forcefully remove & unregister packages").option("-s", "--silent", "do not print anything").option("-v", "--verbose", "print more information for debugging").positionalArgs(true).handler(removeAction);
var remove_default = command;
async function removeAction(packages, options) {
  logger({
    enabled: !options.silent,
    level: options.verbose ? "debug" : "info"
  });
  logger.debug(`Removing plugins:`, packages);
  logger.debug(`Current working directory:`, process.cwd());
  const startTime = Date.now();
  const s = packages.length > 1 ? "s" : "";
  if (packages.length === 0) {
    logger.error(`No packages specified. Use ${color.bold("robo remove <package>")} to remove a plugin.`);
    return;
  }
  const config = await loadConfig("robo", true);
  const pendingRegistration = packages.filter((pkg) => {
    return options.force || config.plugins?.includes(pkg) || config.plugins?.find((p) => Array.isArray(p) && p[0] === pkg);
  });
  logger.debug(`Pending registration remove:`, pendingRegistration);
  const packageJsonPath = path.join(process.cwd(), "package.json");
  const packageJson = require2(packageJsonPath);
  const pendingUninstall = packages.filter((pkg) => {
    return options.force || Object.keys(packageJson.dependencies ?? {})?.includes(pkg);
  });
  logger.debug(`Pending installation remove:`, pendingUninstall);
  if (pendingRegistration.length === 0 && pendingUninstall.length === 0) {
    logger.log("\n" + Indent, `\u{1F5D1}\uFE0F  Plugin${s} already removed.
`);
    return;
  }
  const spinner = new Spinner();
  logger.log("\n" + Indent, color.bold(`\u{1F4E6} Removing plugin${s}`));
  spinner.setText(packages.map((pkg) => `${Indent}    - {{spinner}} ${Highlight(pkg)}`).join("\n") + `

`);
  spinner.start();
  if (pendingUninstall.length > 0) {
    const packageManager = getPackageManager();
    const command2 = packageManager === "npm" ? "uninstall" : "remove";
    logger.debug(`Using package manager:`, packageManager);
    try {
      await exec(`${packageManager} ${command2} ${pendingUninstall.join(" ")}`, {
        stdio: options.force ? "inherit" : "ignore"
      });
      logger.debug(`Successfully uninstalled packages!`);
    } catch (error) {
      logger.error(`Failed to uninstall packages:`, error);
      if (!options.force) {
        return;
      }
    }
  }
  await Promise.all(
    pendingRegistration.map(async (pkg) => {
      return removePluginConfig(pkg);
    })
  );
  spinner.setText(
    pendingRegistration.map((pkg) => `${Indent}    ${HighlightGreen("\u2714 " + pkg)}  `).join("\n") + `

`,
    false
  );
  spinner.stop(false, false);
  logger.log(Indent, `\u{1F5D1}\uFE0F  Plugin${s} successfully removed.
`);
  logger.debug(`Finished in ${Date.now() - startTime}ms`);
}
async function removePluginConfig(pluginName) {
  try {
    const pluginParts = pluginName.replace(/^@/, "").split("/");
    const pluginJs = path.join(process.cwd(), "config", "plugins", ...pluginParts) + ".mjs";
    const pluginTs = path.join(process.cwd(), "config", "plugins", ...pluginParts) + ".ts";
    if (existsSync(pluginJs)) {
      logger.debug(`Deleting ${pluginName} config from ${pluginJs}...`);
      await fs.rm(pluginJs, {
        force: true
      });
    }
    if (existsSync(pluginTs)) {
      logger.debug(`Deleting ${pluginName} config from ${pluginTs}...`);
      await fs.rm(pluginTs, {
        force: true
      });
    }
  } catch (error) {
    logger.error(`Failed to remove plugin config:`, error);
  }
}

export { remove_default as default, removeAction };
